package com.saicmotor.room;

import androidx.appcompat.app.AppCompatActivity;
import androidx.room.Room;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.saicmotor.room.Dao.UserDao;
import com.saicmotor.room.Database.UserDatabase;
import com.saicmotor.room.Entity.User;

import java.util.List;

public class MainActivity extends AppCompatActivity {

    UserDao userDao;
    UserDatabase database;
    User user;
    TextView tv;
    EditText first, second;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = findViewById(R.id.tv);
        first = findViewById(R.id.et_1);
        second = findViewById(R.id.et_2);

        // 初始化数据库、数据、DAO
        database = UserDatabase.getInstance(this);
        userDao = database.getUserDao();

        // 插入
        ((Button) findViewById(R.id.bt_1)).setOnClickListener(o -> {
            user=new User();
            user.firstName = first.getText().toString();
            user.secondName = second.getText().toString();
            userDao.insert(user);
            String msg = "插入：firstname："
                    + user.firstName + "lastname:" + user.secondName;
            Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
            tv.setText(msg);
        });

        // 查询
        ((Button) findViewById(R.id.bt_2)).setOnClickListener(o -> {
                List<User> users = userDao.getAllUsers();
                StringBuilder str = new StringBuilder("user:");
                for (int i = 0; i < users.size(); i++) {
                    str.append("firstname" + users.get(i).firstName + "secondname" + users.get(i).secondName+"\\n");
                    Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();
                    tv.setText(str);
                }
        });

        // 删除
    }
}